import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import {
  Row,
  Col,
  Card,
  Form,
  Input,
  Button,
  Divider, message, DatePicker, Modal,
} from 'antd';
import DragTable from '@/components/DragTable';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import UpdateForm from './createFrom';
import DescView from './descView';
import styles from '../UserManage.less';
import { powerBtnFunc } from '@/utils/utils';

const FormItem = Form.Item;

/* eslint react/no-multi-comp:0 */
@connect(({ BrandManage, loading }) => ({
  BrandManage,
  loading: loading.models.BrandManage,
}))

@Form.create()
class BrandManage extends PureComponent {
  state = {
    modalVisible: false,
    updateModalVisible: false,
    lookDescView: false,
    selectedRows: {},
    formValues: {},
    pagination: {
      pageNo: 1,
      pageSize: 15,
    },
  };

  constructor(props) {
    super(props);
  }

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'BrandManage/fetch',
    });
  }


  columns = [
    {
      title: '品牌编号',
      dataIndex: 'brandNo',
    },
    {
      title: '品牌名称',
      dataIndex: 'brandName',
    },
    {
      title: 'LOGO',
      dataIndex: 'brandLogo',
      render: val => <img className={styles.brandLogo} src={val} alt=""/>,

    },

    {
      title: '创建人',
      dataIndex: 'createName',
    },

    {
      title: '创建时间',
      dataIndex: 'createTime',
    },


    {
      title: '状态',
      dataIndex: 'status',
      render: val => <span>{val === 1 ? '启用' : '停用'}</span>,
    },
    {
      title: '操作',
      render: (text, record) => (
        <Fragment>
          {powerBtnFunc('100026',
            [<a key={'edit'} onClick={() => this.handleUpdateModalVisible(true, record)}>修改</a>,
              <Divider key={'divider'} type="vertical"/>],
          )}
          {powerBtnFunc('100027',

            [<a key={'view'} onClick={() => this.handleLookDesc(true, record)}>查看</a>,
              <Divider key={'divider'} type="vertical"/>],
          )}
          {powerBtnFunc('100030',

            [<a key={'del'} onClick={() => this.handleDel(record)}>删除</a>,
              <Divider key={'divider'} type="vertical"/>],
          )}

          {powerBtnFunc('100029',
            <a key={'status'} onClick={() => this.onChange(record)}>{record.status === 1 ? '停用' : '启用'}</a>,
          )}

        </Fragment>
      ),
    },
  ];

  onChange(record) {

    const { dispatch } = this.props;
    const { pagination } = this.state;
    Modal.confirm({
      title: `确定`,
      content: `你确定${record.status === 1 ? '停用' : '启用'}该品牌吗?`,
      okText: '确认',
      cancelText: '取消',
      onOk() {
        dispatch({
          type: 'BrandManage/status',
          payload: {
            brandNo: record.brandNo,
            status: record.status === 1 ? 2 : 1,
          },
          callback: (res) => {
            if (res.code === 200) {
              message.success('修改成功');
              dispatch({
                type: 'BrandManage/fetch',
                payload: pagination,
              });
            } else {
              message.error(res.errMsg);
            }
          },
        });
      },
    });
  }

  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;
    const { formValues } = this.state;

    this.setState({
      pagination: {
        pageNo: pagination.current,
        pageSize: 15,
      },
    });
    const params = {
      pageNo: pagination.current,
      pageSize: 15,
      ...formValues,
    };

    dispatch({
      type: 'BrandManage/fetch',
      payload: params,
    });
  };
  //重置
  handleFormReset = () => {
    const { form, dispatch } = this.props;
    form.resetFields();
    this.setState({
      formValues: {},
    });
    dispatch({
      type: 'BrandManage/fetch',
      payload: {},
    });
  };

  handleDel = row => {

    const { dispatch } = this.props;
    const { pagination } = this.state;
    Modal.confirm({
      title: '确认',
      content: '确定删除该品牌吗？',
      okText: '确认',
      cancelText: '取消',
      onOk: () => {
        dispatch({
          type: 'BrandManage/remove',
          payload: {
            code: row.brandNo,
          },
          callback: (res) => {
            if (res.code === 200) {
              message.success('删除成功');
              dispatch({
                type: 'BrandManage/fetch',
                payload: pagination,
              });
            } else {
              message.error(res.errMsg);
            }
          },
        });
      },
    });
  };
  moveRow = (dragIndex, hoverIndex) => {
    const { BrandManage: { data } } = this.props;
    const { dispatch } = this.props;
    const { pagination } = this.state;
    dispatch({
      type: 'BrandManage/brandSort',
      payload: {
        firstSort: data.data[dragIndex].brandNo,
        secondSort: data.data[hoverIndex].brandNo,
      },
      callback: (res) => {
        if (res.code === 200) {
          message.success('交换成功');
          this.setState({
            selectedRows: [],
          });
          dispatch({
            type: 'BrandManage/fetch',
            payload: pagination,
          });
        } else {
          message.error(res.errMsg);
        }
      },
    });
  };

  //搜索
  handleSearch = e => {
    e.preventDefault();
    const { dispatch, form } = this.props;
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      const values = {
        ...fieldsValue,
      };
      this.setState({
        formValues: values,
      });

      dispatch({
        type: 'BrandManage/fetch',
        payload: values,
      });
    });
  };
  //新建显示窗口
  handleModalVisible = flag => {
    this.setState({
      modalVisible: !!flag,
      updateModalVisible: !!flag,
      selectedRows: {},
    });
  };
  //修改
  handleUpdateModalVisible = (flag, record) => {
    console.log(record);
    this.setState({
      updateModalVisible: !!flag,
      modalVisible: !flag,
      selectedRows: record,
      formVals: record,
    });
  };
  //查看
  handleLookDesc = (flag, record) => {
    this.setState({
      lookDescView: !!flag,
      selectedRows: record,
    }, () => {
      if (!!flag) {
        const { dispatch } = this.props;
        dispatch({
          type: 'BrandManage/getDesc',
          payload: { adminNo: record.brandNo },
        });
      }
    });

  };
  // 新建请求
  handleAdd = fields => {
    const { dispatch } = this.props;
    dispatch({
      type: 'BrandManage/add',
      payload: fields,
      callback: (response) => {
        dispatch({
          type: 'BrandManage/fetch',
        });
      },
    });

    this.handleModalVisible();
  };
  // 修改请求
  handleUpdate = fields => {
    const { dispatch } = this.props;
    const { pagination } = this.state;
    dispatch({
      type: 'BrandManage/update',
      payload: fields,
      callback: () => {
        dispatch({
          type: 'BrandManage/fetch',
          payload: pagination,

        });
        this.handleUpdateModalVisible(false, []);
      },
    });

  };

  renderSimpleForm() {
    const {
      form: { getFieldDecorator },
    } = this.props;
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="品牌编号">
              {getFieldDecorator('brandNo')(<Input placeholder="请输入"/>)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="品牌名称">
              {getFieldDecorator('brandName')(<Input placeholder="请输入品牌名称"/>)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="开始时间">
              {getFieldDecorator('startTime')(<DatePicker placeholder="选择开始时间"
                                                          style={{ width: '100%' }}/>)}
            </FormItem>
          </Col>
        </Row>
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>


          <Col md={8} sm={24}>
            <FormItem label="结束时间">
              {getFieldDecorator('endTime')(
                <DatePicker placeholder="选择结束时间"
                            style={{ width: '100%' }}/>)}
            </FormItem>
          </Col>

          <Col md={8} sm={24}>
        <span className={styles.submitButtons}>
        <Button type="primary" htmlType="submit">
        查询
        </Button>
        <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
        重置
        </Button>

        </span>
          </Col>
        </Row>
      </Form>
    );
  }


  render() {
    const { BrandManage: { data, Desc }, loading } = this.props;
    const { selectedRows, modalVisible, updateModalVisible, lookDescView } = this.state;

    const parentMethods = {
      handleAdd: this.handleAdd,
      handleModalVisible: this.handleModalVisible,
      handleUpdateModalVisible: this.handleUpdateModalVisible,
      handleUpdate: this.handleUpdate,
    };
    return (
      <PageHeaderWrapper title="品牌管理">
        <Card bordered={false}>

          <div className={styles.tableList}>
            <div className={styles.tableListForm}>{this.renderSimpleForm()}</div>
            <div className={styles.tableListOperator}>
              {powerBtnFunc('100025',
                <Button icon="plus" key={'create'} type="primary" onClick={() => this.handleModalVisible(true)}>
                  新建
                </Button>,
              )}

            </div>
            <DragTable
              selectedRows={selectedRows}
              loading={loading}
              data={data ? data : []}
              rowKey='brandNo'
              moveRow={this.moveRow}
              columns={this.columns}
              onChange={this.handleStandardTableChange}
            />
          </div>
        </Card>
        <DescView
          handleLookDesc={this.handleLookDesc}
          selectedRows={Desc ? Desc : {}}
          lookDescView={lookDescView}/>

        <UpdateForm
          {...parentMethods}
          updateModalVisible={updateModalVisible}
          modalVisible={modalVisible}
          values={selectedRows}
        />
      </PageHeaderWrapper>
    );
  }
}

export default BrandManage;
